﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.HtmlControls;
using DataAccess;
using com.chttl.ienc.bean;
using java.util;

namespace iEN.Organization
{
    public partial class TagManage : System.Web.UI.Page
    {
        #region protected void Page_Load(object sender, EventArgs e) //初始頁面
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.Page.IsPostBack)//先判斷是否已經登入過
            {                
                if (Session["LoginName"] == null)
                {
                    Response.Write("<script>alert('請先登入！！');location.href='../Login.aspx';</script>");
                }
                this.Intialize(); 
            }

            if (Session["SysAdmin"].ToString() != "2")
            {
                Panel1.Visible = false;
                Panel2.Visible = false;
                lblMsg.Visible = true;
                btAddTag.Visible = false;
                btReturn.Visible = false;
            }
        }
        #endregion

        #region Initialization methods
        private void Intialize()
        {
            ddlControl.Items.Clear();
            ddlDevice.Items.Clear();
            //加一個空白的選項於最上方
            ListItem empty = ddlControl.Items.FindByText(string.Empty);
            if (empty == null)
            {
                ddlControl.Items.Add(new ListItem(string.Empty));
                ddlDevice.Items.Add(new ListItem(string.Empty));
            }

            DataTable dttmp = new DBAccess().getControllerTable("1");  //取得ALLControl
            if (dttmp == null)
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('資料庫抓取資料有誤！')", true);
                return;
            }
            for (int i = 0; i < dttmp.Rows.Count; i++)
            {
                //this.ddlControl.DataValueField = dttmp.Rows[i]["_id"].ToString();
                //this.ddlControl.DataTextField = dttmp.Rows[i]["_name"].ToString();
                this.ddlControl.Items.Add(new ListItem(dttmp.Rows[i]["_name"].ToString(), dttmp.Rows[i]["_id"].ToString()));
            }

            DataTable dtTemp = new DBAccess().getTagTable("1");  //取得ALLTag
            Session["dtDataSourceTemp"] = dtTemp;
        }
        #endregion

        #region //分頁設定
        protected void First_Click(object sender, EventArgs e)
        {
            int intPageIndex = 0;
            Button lkbtn = (Button)sender;
            switch (lkbtn.CommandArgument.ToString())
            {
                case "Previous":
                    if (this.gvGrpName.PageIndex > 0)
                        intPageIndex = this.gvGrpName.PageIndex - 1;
                    break;
                case "Next":
                    if (this.gvGrpName.PageIndex < this.gvGrpName.PageCount - 1)
                        intPageIndex = this.gvGrpName.PageIndex + 1;
                    break;
                case "Last":
                    intPageIndex = this.gvGrpName.PageCount - 1;
                    break;
            }
            this.gvGrpName.DataSource = (DataTable)Session["dtDataSourceTemp"];
            this.gvGrpName.PageIndex = intPageIndex;
            this.gvGrpName.DataBind();
        }

        protected void Previous_Click(object sender, EventArgs e)
        {
            int intPageIndex = 0;
            Button lkbtn = (Button)sender;
            switch (lkbtn.CommandArgument.ToString())
            {
                case "Previous":
                    if (this.gvGrpName.PageIndex > 0)
                        intPageIndex = gvGrpName.PageIndex - 1;
                    break;
                case "Next":
                    if (this.gvGrpName.PageIndex < this.gvGrpName.PageCount - 1)
                        intPageIndex = this.gvGrpName.PageIndex + 1;
                    break;
                case "Last":
                    intPageIndex = gvGrpName.PageCount - 1;
                    break;
            }
            this.gvGrpName.DataSource = (DataTable)Session["dtDataSourceTemp"];
            this.gvGrpName.PageIndex = intPageIndex;
            this.gvGrpName.DataBind();
        }

        protected void Next_Click(object sender, EventArgs e)
        {
            int intPageIndex = 0;
            Button lkbtn = (Button)sender;
            switch (lkbtn.CommandArgument.ToString())
            {
                case "Previous":
                    if (this.gvGrpName.PageIndex > 0)
                        intPageIndex = this.gvGrpName.PageIndex - 1;
                    break;
                case "Next":
                    if (this.gvGrpName.PageIndex < this.gvGrpName.PageCount - 1)
                        intPageIndex = gvGrpName.PageIndex + 1;
                    break;
                case "Last":
                    if (this.gvGrpName.PageIndex != this.gvGrpName.PageCount)
                        intPageIndex = this.gvGrpName.PageCount - 1;
                    break;
            }
            this.gvGrpName.DataSource = (DataTable)Session["dtDataSourceTemp"];
            this.gvGrpName.PageIndex = intPageIndex;
            this.gvGrpName.DataBind();

        }

        protected void Last_Click(object sender, EventArgs e)
        {
            int intPageIndex = 0;
            Button lkbtn = (Button)sender;
            switch (lkbtn.CommandArgument.ToString())
            {
                case "Previous":
                    if (this.gvGrpName.PageIndex > 0)
                        intPageIndex = this.gvGrpName.PageIndex - 1;
                    break;
                case "Next":
                    if (this.gvGrpName.PageIndex < this.gvGrpName.PageCount - 1)
                        intPageIndex = this.gvGrpName.PageIndex + 1;
                    break;
                case "Last":
                    intPageIndex = this.gvGrpName.PageCount - 1;
                    break;
            }
            this.gvGrpName.DataSource = (DataTable)Session["dtDataSourceTemp"];
            this.gvGrpName.PageIndex = intPageIndex;
            this.gvGrpName.DataBind();

        }

        protected void dd1PageJump_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList ddlpage = ((DropDownList)this.gvGrpName.BottomPagerRow.FindControl("dd1PageJump"));
            this.gvGrpName.DataSource = (DataTable)Session["dtDataSourceTemp"];
            this.gvGrpName.PageIndex = ddlpage.SelectedIndex;
            this.gvGrpName.DataBind();

        }

        public void pageSet(object gvQuery)
        {
            GridView gv = (GridView)gvQuery;
            if (gv.PageCount > 1)
            {
                if (gv.BottomPagerRow == null)
                    return;
                Label lbCount = (Label)gv.BottomPagerRow.FindControl("lbAllCount");
                Label lbPage = (Label)gv.BottomPagerRow.FindControl("lbAllPage");
                DropDownList ddlJump = (DropDownList)gv.BottomPagerRow.FindControl("dd1PageJump");
                //顯示資料總筆數與總頁數
                lbCount.Text = "共" + (gv.PageSize * gv.PageCount).ToString() + "筆";
                lbPage.Text = "共" + gv.PageCount + "頁";
                //設定下拉選單跳頁之頁數        
                for (int i = 1; i <= gv.PageCount; i++)
                    ddlJump.Items.Add(new ListItem(i.ToString()));
                //first:firstc和previous按鈕無作用;  last: next和last按鈕無作用  
                if (gv.PageIndex == 0)
                {
                    ((Button)gv.BottomPagerRow.FindControl("First")).Enabled = false;
                    ((Button)gv.BottomPagerRow.FindControl("Previous")).Enabled = false;
                }
                else if (gv.PageIndex == (gv.PageCount - 1))
                {
                    ((Button)gv.BottomPagerRow.FindControl("Next")).Enabled = false;
                    ((Button)gv.BottomPagerRow.FindControl("Last")).Enabled = false;
                }
                //顯示目前頁數
                ddlJump.SelectedIndex = gv.PageIndex;
            }
        }
        #endregion

        #region protected void btReturn_Click(object sender, EventArgs e) //回到設備管理頁面
        protected void btReturn_Click(object sender, EventArgs e)
        {
            this.Page.Response.Redirect("../Organization/DeviceManage.aspx");
        }
        #endregion

        protected void gvGrpName_DataBound(object sender, EventArgs e)
        {
            pageSet(this.gvGrpName);
            gvGrpName.SelectedIndex = -1;
        }

        protected void ddlDevice_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.Panel1.Visible = true;
            DataTable dtTag = new DBAccess().getTagTable("1");  //取得ALLTag
            dtTag.DefaultView.RowFilter = "_device_id=" + this.ddlDevice.SelectedValue.ToString();
            dtTag = dtTag.DefaultView.ToTable();
            if (dtTag == null)
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('資料庫抓取資料有誤！')", true);
                return;
            }
            this.gvGrpName.DataSource = dtTag;
            this.gvGrpName.DataBind();

            //取得控制器型態:FATEK or MODBUS
            DataTable dtDev = new DBAccess().getDeviceTable("1");
            dtDev.DefaultView.RowFilter ="_id="+ this.ddlDevice.SelectedValue.ToString();
            dtDev=dtDev.DefaultView.ToTable();
            DataTable dtControl = new DBAccess().getControllerTable("1");
            dtControl.DefaultView.RowFilter = "_id=" + dtDev.Rows[0]["_controller_id"].ToString();
            dtControl = dtControl.DefaultView.ToTable();
            Session["Protocol"] = dtControl.Rows[0]["_protocol"].ToString();
        }

        protected void ddlControl_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlDevice.Items.Clear();
            ddlDevice.Items.Add(new ListItem(string.Empty));
            this.Panel1.Visible = false;

            DataTable dtDevice = new DBAccess().getDeviceTable("1");  //取得ALLDevice
            if (dtDevice == null)
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('資料庫抓取資料有誤！')", true);
                return;
            }
            else
            {
                dtDevice.DefaultView.RowFilter = "_controller_id=" + this.ddlControl.SelectedValue.ToString();
                dtDevice = dtDevice.DefaultView.ToTable();
                for (int i = 0; i < dtDevice.Rows.Count; i++)
                {
                    this.ddlDevice.Items.Add(new ListItem(dtDevice.Rows[i]["_name"].ToString(), dtDevice.Rows[i]["_id"].ToString()));
                }
            }
        }

        #region protected void btAddTag_Click(object sender, EventArgs e) //新增監控點
        protected void btAddTag_Click(object sender, EventArgs e)
        {
            gvGrpName.SelectedIndex = -1;
            
            this.UpdatePanel3.Visible =true;
            this.UpdatePanel2.Visible = false;
        }
        #endregion

        #region protected void gvGrpName_RowDeleting(object sender, GridViewDeleteEventArgs e) //刪除監控點
        protected void gvGrpName_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            //DataTable dtTemp = (DataTable)Session["dtDataSourceTemp"];
            //int tagId = Convert.ToInt32(dtTemp.Rows[e.RowIndex]["_id"].ToString());
            //bool temp = new WebService().removeTag1(tagId);
            
            string tagID = this.gvGrpName.Rows[e.RowIndex].Cells[0].Text;

            string strAccount = Session["LoginAccount"].ToString();
            string strIP = Session["LoginIP"].ToString();
            string strMemo = "ID：" + tagID + "//名稱：" + this.gvGrpName.Rows[e.RowIndex].Cells[1].Text;

            bool blnRet = new DBAccess().deleteTagData(tagID);

            if (blnRet == false)
            {
                new DBAccess().addEventLog(strAccount, strIP, 52, strMemo, "0");
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('刪除監控點資料有誤！')", true);
                //return;
            }
            {
                new DBAccess().addEventLog(strAccount, strIP, 52, strMemo, "1");
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('刪除監控點資料成功！')", true);
                //return;
            }
            //this.Page.Response.Redirect("../Organization/TagManage.aspx");
            this.UpdatePanel3.Visible = false;
            this.UpdatePanel2.Visible = false;
            ddlDevice_SelectedIndexChanged(this, null);
        }
        #endregion

        #region protected void NoAdd_Click(object sender, EventArgs e) //取消新增
        protected void NoAdd_Click(object sender, EventArgs e)
        {
            this.UpdatePanel3.Visible = false;
            this.Page.Response.Redirect("../Organization/TagManage.aspx");
        }
        #endregion

        #region protected void NoEdit_Click(object sender, EventArgs e) //取消修改
        protected void NoEdit_Click(object sender, EventArgs e)
        {
            this.UpdatePanel2.Visible = false;
            this.Page.Response.Redirect("../Organization/TagManage.aspx");
        }
        #endregion

        #region protected void YesEdit_Click(object sender, EventArgs e) //確定修改
        protected void YesEdit_Click(object sender, EventArgs e)
        {
            //DataTable dtTemp = (DataTable)Session["dtDataSourceTemp"];
            //int tagId=Convert.ToInt32(dtTemp.Rows[Convert.ToInt32(Session["EditIndex"])]["_id"].ToString());
            //Tag modTag = new WebService().getTag1(tagId);
            //modTag.setName(TagName.Text);
            //modTag.setDescription(tbShowText.Text);
            //modTag.setUnit(tbUnit.Text);
            //modTag.setWeight(Convert.ToDouble(tbWeight.Text));
            //modTag.setBias(Convert.ToDouble(tbBias.Text.ToString()));
            //modTag.setDescription(DeviceDesc.Text);
            //modTag.setEnabled(true);
            //modTag.setDatetime(new Date());
            //Tag temp = new WebService().modifyTag1(modTag);
            string strTagID = Session["TagID"].ToString();

            try
            {
                bool blnRet = new DBAccess().updateTagData(strTagID, int.Parse(StrName.SelectedValue), Attribute.SelectedValue, TagName.Text,
                    tbShowText.Text, DeviceDesc.Text, tbUnit.Text, double.Parse(tbWeight.Text), double.Parse(tbBias.Text), Resig.SelectedValue, DataType.SelectedValue,
                    DataLong.SelectedValue, int.Parse(tbBitAddressUpdate.Text), tbRegisterAddressUpdate.Text, int.Parse(HigLow.SelectedValue));

                string strAccount = Session["LoginAccount"].ToString();
                string strIP = Session["LoginIP"].ToString();
                string strMemo = "ID：" + strTagID + "//名稱：" + TagName.Text;

                if (blnRet == false)
                {
                    new DBAccess().addEventLog(strAccount, strIP, 53, strMemo, "0");
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('修改監控點資料有誤！')", true);
                    //return;
                }
                else
                {
                    new DBAccess().addEventLog(strAccount, strIP, 53, strMemo, "1");
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('修改監控點資料成功！')", true);
                    //return;
                }
            }
            catch
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('修改監控點資料有誤！')", true);
            }
            Panel3Clear();
            this.UpdatePanel2.Visible = false;
            //this.Page.Response.Redirect("../Organization/TagManage.aspx");
            ddlDevice_SelectedIndexChanged(this, null);
        }
        #endregion

        #region protected void YesAdd_Click(object sender, EventArgs e) //確定新增
        protected void YesAdd_Click(object sender, EventArgs e)
        {
            Tag addTag;
            string protocol = (string)Session["Protocol"];
            //if (protocol == "FATEK")
            //{
            //    FatekTag FaiTag = new FatekTag();
            //    FaiTag.setEnabled(true);
            //    FaiTag.setType(-1);
            //    FaiTag.setAttribute(ddlAttribute.SelectedValue);
            //    FaiTag.setModel(1);
            //    FaiTag.setName(tbName.Text);
            //    FaiTag.setWeight(Convert.ToDouble(Weight.Text));
            //    FaiTag.setBias(Convert.ToDouble(Bias.Text));
            //    FaiTag.setFormula(0);
            //    FaiTag.setSpetialAction(0);
            //    FaiTag.setModelType(ddlR.SelectedValue);
            //    FaiTag.setDatatype(ddlDataType.SelectedValue);
            //    FaiTag.setDataLength(ddlDataLong.SelectedValue);
            //    FaiTag.setBitAddress(0);
            //    FaiTag.setRegisterAddress("DD01438"); //TextBox23.Text
            //    FaiTag.setNode(ddlAttribute.SelectedValue); 
            //    FaiTag.setEndianness(0);
            //    FaiTag.setCustomerId(1);
            //    FaiTag.setControllServerId(1);
            //    FaiTag.setControllerId(Convert.ToInt32(ddlControl.SelectedValue));
            //    FaiTag.setDeviceId(Convert.ToInt32(ddlDevice.SelectedValue));
            //    FaiTag.setSigned(true);
            //    FaiTag.setDescription(Des.Text);
            //    FaiTag.setUnit(Unit.Text);

            //    addTag = new WebService().createTag1(FaiTag);
            //    if (addTag == null)
            //    {
            //        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('新增監控點資料有誤！')", true);
            //        return;
            //    }

            //}
            //else //MODBUS
            //{
                //ModbusTag MaiTag = new ModbusTag();
                //MaiTag.setEnabled(true);
                //MaiTag.setType(-1);
                //MaiTag.setAttribute(ddlAttribute.SelectedValue);
                //MaiTag.setModel(2);
                //MaiTag.setName(tbName.Text);
                //MaiTag.setWeight(Convert.ToDouble(Weight.Text));
                //MaiTag.setBias(Convert.ToDouble(Bias.Text));
                //MaiTag.setFormula(0);
                //MaiTag.setSpetialAction(0);
                //MaiTag.setModelType(ddlR.SelectedValue);
                //MaiTag.setDatatype(ddlDataType.SelectedValue);
                //MaiTag.setDataLength(ddlDataLong.SelectedValue);
                //MaiTag.setBitAddress(-1);
                //MaiTag.setRegisterAddress(tbRegisterAddressAdd.Text);
                //MaiTag.setEndianness(0);
                //MaiTag.setCustomerId(1);
                //MaiTag.setControllServerId(1);
                //MaiTag.setControllerId(Convert.ToInt32(ddlControl.SelectedValue));
                //MaiTag.setDeviceId(Convert.ToInt32(ddlDevice.SelectedValue));
                //MaiTag.setDescription(Des.Text);
                //MaiTag.setUnit(Unit.Text);

                //addTag = new WebService().createTag1(MaiTag);

            DataTable dtController = new DBAccess().getControllerTable("1");  //取得ALLOrgGroup
            dtController.DefaultView.RowFilter = "_id=" + ddlControl.SelectedValue;
            dtController = dtController.DefaultView.ToTable();

            bool blnRet = new DBAccess().addTagData(dtController.Rows[0]["_ctrl_server_id"].ToString(), ddlControl.SelectedValue, ddlDevice.SelectedValue, Convert.ToInt32(ddlStrName.SelectedValue), ddlAttribute.SelectedValue
                , tbName.Text, tbShow.Text, Des.Text, Unit.Text, Convert.ToDouble(Weight.Text), Convert.ToDouble(Bias.Text), ddlR.SelectedValue
                , ddlDataType.SelectedValue, ddlDataLong.SelectedValue, Convert.ToInt32(tbBitAddressAdd.Text), tbRegisterAddressAdd.Text, Convert.ToInt32(ddlHL.SelectedValue));

            string strAccount = Session["LoginAccount"].ToString();
            string strIP = Session["LoginIP"].ToString();
            string strMemo = "名稱：" + tbName.Text;

                if (blnRet == false)
                {
                    new DBAccess().addEventLog(strAccount, strIP, 51, strMemo, "0");
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('新增監控點資料有誤！')", true);
                    //return;
                }
                else
                {
                    new DBAccess().addEventLog(strAccount, strIP, 51, strMemo, "1");
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('新增監控點資料成功！')", true);
                }
            //}
            Panel4Clear();
            this.UpdatePanel3.Visible = false;

            ddlDevice_SelectedIndexChanged(this, null);
            //this.Page.Response.Redirect("../Organization/TagManage.aspx");            
        }
        #endregion

        #region protected void gvGrpName_SelectedIndexChanging(object sender, GridViewSelectEventArgs e) //修改監控點
        protected void gvGrpName_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {
            this.UpdatePanel3.Visible = false;            
            this.UpdatePanel2.Visible = true;

            Session["EditIndex"] = e.NewSelectedIndex;
            Session["TagID"] = this.gvGrpName.Rows[e.NewSelectedIndex].Cells[0].Text;

            DataTable dtTag = new DBAccess().getTagTable("1");
            dtTag.DefaultView.RowFilter = "_id=" + this.gvGrpName.Rows[e.NewSelectedIndex].Cells[0].Text;
            dtTag = dtTag.DefaultView.ToTable();

            if (dtTag != null && dtTag.Rows.Count == 1)
            {
                TagName.Text = dtTag.Rows[0]["_name"].ToString();
                tbShowText.Text = dtTag.Rows[0]["_label"].ToString();
                StrName.SelectedValue = dtTag.Rows[0]["_type"].ToString();
                Attribute.SelectedValue = dtTag.Rows[0]["_attribute"].ToString();
                tbUnit.Text = dtTag.Rows[0]["_unit"].ToString();
                tbWeight.Text = dtTag.Rows[0]["_weight"].ToString();
                tbBias.Text = dtTag.Rows[0]["_bias"].ToString();
                DeviceDesc.Text = dtTag.Rows[0]["_desc"].ToString();
            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('監控點資料有誤，請連絡系統人員！')", true);
            }

            DataTable dtModbusTag = new DBAccess().getModbusTagTable(this.gvGrpName.Rows[e.NewSelectedIndex].Cells[0].Text);
            if (dtModbusTag !=null && dtModbusTag.Rows.Count == 1)
            {
                Resig.SelectedValue = dtModbusTag.Rows[0]["_model_type"].ToString();
                DataType.SelectedValue = dtModbusTag.Rows[0]["_data_type"].ToString();
                DataLong.SelectedValue = dtModbusTag.Rows[0]["_data_length"].ToString();
                HigLow.SelectedValue = dtModbusTag.Rows[0]["_endianness"].ToString();

                tbBitAddressUpdate.Text = dtModbusTag.Rows[0]["_bit_address"].ToString();
                tbRegisterAddressUpdate.Text = dtModbusTag.Rows[0]["_register_address"].ToString();
            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('監控點資料有誤，請連絡系統人員！')", true);
            }

        }
        #endregion

        protected void gvGrpName_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            e.Row.Cells[0].Visible = false;
        }

        #region private void Panel4Clear() //清除新增資料
        private void Panel4Clear()
        {
            tbName.Text = "";
            tbShow.Text = "";
            ddlStrName.SelectedIndex = 0;
            ddlAttribute.SelectedIndex = 0;
            Unit.Text = "";
            Weight.Text = "";
            Bias.Text = "";
            ddlR.SelectedIndex = 0;
            ddlDataType.SelectedIndex = 0;
            ddlDataLong.SelectedIndex = 0;
            tbBitAddressAdd.Text = "";
            tbRegisterAddressAdd.Text = "";
            ddlHL.SelectedIndex = 0;
            Des.Text = "";
        }
        #endregion

        #region private void Panel3Clear() //清除修改資料
        private void Panel3Clear()
        {
            TagName.Text = "";
            tbShowText.Text = "";
            StrName.SelectedIndex = 0;
            Attribute.SelectedIndex = 0;
            tbUnit.Text = "";
            tbWeight.Text = "";
            tbBias.Text = "";
            Resig.SelectedIndex = 0;
            DataType.SelectedIndex = 0;
            DataLong.SelectedIndex = 0;
            tbBitAddressUpdate.Text = "";
            tbRegisterAddressUpdate.Text = "";
            HigLow.SelectedIndex = 0;
            DeviceDesc.Text = "";
        }
        #endregion
    }
}